package codec

import (
	"encoding/hex"
	"log"
	"strconv"
)

func DecoderData(data []byte) *DataDockPackage {
	for len(data) > 12 {
		//log.Println("###开始解码")
		size := len(data)
		//log.Println("###数组总长",size)
		//1.请求头验证
		headerbyte := data[0:2]
		data = data[2:size]
		header := hex.EncodeToString(headerbyte)
		log.Println("帧头:", header, "数据:", data)
		if header != "5a55" {
			log.Println("##帧头不正确,跳过本次循环")
			continue //跳过当前循环
		}

		//2.获取帧长度
		lengthbyte := data[0:4]
		data = data[4:size]
		lengthhex := hex.EncodeToString(lengthbyte)
		//log.Println("hexlength",lengthhex)
		length, _ := strconv.ParseUint(lengthhex, 16, 32) //16进制转10进制
		//log.Println("长度:",length)

		//3.获取帧流水号
		serialNumb := data[0:2]
		data = data[2:size]
		serialNumh := hex.EncodeToString(serialNumb)
		serialNum, _ := strconv.ParseUint(serialNumh, 16, 32) //16进制转10进制
		//log.Println("###流水号:",serialNum)
		//4.协议版本
		versionb := data[0:1]
		data = data[1:size]
		versionh := hex.EncodeToString(versionb)
		version, _ := strconv.ParseUint(versionh, 16, 32) //16进制转10进制
		//log.Println("###协议版本",version)
		//5.命令
		cmdb := data[0:1]
		data = data[1:size]
		cmdh := hex.EncodeToString(cmdb)
		//log.Println("####命令",cmdh)
		//6. 数据载荷
		datainfolength := length - 4 - 2 - 1 - 1 - 1
		//log.Println("###数据载荷长度",datainfolength,"##data长度",len(data))
		datainfob := data[0:datainfolength]
		data = data[datainfolength:size]
		datainfoh := hex.EncodeToString(datainfob) //数据

		//7.校验和
		checksumb := data[0:1]
		//data:=data[0:1]
		checksumh := hex.EncodeToString(checksumb)
		checksum, _ := strconv.ParseUint(checksumh, 16, 32) //16进制转10进制
		return NewDataDpckPackage(serialNum, version, checksum, cmdh, datainfoh)
	}
	return nil
}
